﻿#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QByteArray>
#include <QFileDialog>
#include <QTextStream>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_openBtn_clicked()
{
    //获取文件路径
    QString strOpenFileName = QFileDialog::getOpenFileName(this, QStringLiteral("打开文件"),
                                                       ".", "Files (*.json)");
    if (strOpenFileName.isEmpty()) {
        return;
    }

    QFile openFile(strOpenFileName);
    bool isOpenOk = openFile.open(QIODevice::ReadOnly);

    //判断如果文件打开失败，直接返回，不做操作,成功在接着往下
    if(!isOpenOk)
    {
        qWarning() << "file open error!";
        return;
    }

    //从json文件中读取全部内容
    QString strJson = openFile.readAll();
    QJsonParseError parseJsonErr;
    QJsonDocument document = QJsonDocument::fromJson(strJson.toUtf8(), &parseJsonErr);
    if(parseJsonErr.error != QJsonParseError::NoError)
    {
        qWarning()<<tr("Analysis json error!");
        return;
    }

    QString strSaveFileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                    "./productshow.json", tr("json Files(*.json)"));
    if (strSaveFileName.isEmpty())
    {
        return;
    }
    QFile saveFile(strSaveFileName); //关联文件名字
    //只写方式打开文件
    bool isSaveOk = saveFile.open(QIODevice::WriteOnly);
    if(!isSaveOk)
    {
        qWarning() << "open file error where create!";
        return;
    }

    saveFile.write(document.toBinaryData().toHex().toBase64());

    openFile.close();
    saveFile.close();
}
